import { Component, Input, OnInit } from "@angular/core";
import { Pnode } from "src/app/@types/pnode";
import { NodeFactoryService } from "src/app/server/node-factory.service";
import { ProcessService } from "src/app/server/process.service";
import differenceInCalendarDays from "date-fns/differenceInCalendarDays";
import setHours from "date-fns/setHours";
import { NzModalService } from "ng-zorro-antd/modal";
import { NzNotificationService } from "ng-zorro-antd/notification";

@Component({
    selector: "condition-pnode-time",
    styles: [``],
    templateUrl: "./condition-pnode-time.component.html",
})
export class ConditionPnodeTimeComponent implements OnInit {
    /** 节点数据 */
    @Input() data: Pnode;

    visible = false;
    /** 最大分支数 */
    maxBranchs = 4;
    /** 时间段 */
    timeArr = [];
    /** 时间段缓存 */
    timeArrCache = [];

    constructor(
        private pSrv: ProcessService,
        private nfSrv: NodeFactoryService,
        private modal: NzModalService,
        private notification: NzNotificationService
    ) {}
    timeDefaultValue = setHours(new Date(), 0);

    ngOnInit(): void {}

    confirm() {
        const { x, y, id, pid } = this.data;
        const removeNodes = this.pSrv.DB.childrenDeepFlatten({ id });
        const deleteYLevel = removeNodes.sort((a, b) => b.y - a.y)[0]["y"];
        const targetYLevel = deleteYLevel + 1;
        const changeValue = y - deleteYLevel;

        const helpNode = this.nfSrv.createHelperPnode(x, y, pid);
        this.pSrv
            .remove(removeNodes)
            .insert(helpNode)
            .move(targetYLevel, changeValue)
            .updatePedges();
    }

    /** 打开抽屉 */
    openDrawwe() {
        // 获取所有的时间点
        this.visible = true;
        this.getTimeArr();
    }
    closeDrawer() {
        this.visible = false;
    }

    getTimeArr() {
        const { id, x } = this.data;
        const children = this.pSrv.DB.childrenDeepFlatten({ id });
        // this.timeArrCache = children.filter((it) => it.x === x + 1);
        // this.timeArr = this.easyCopy(this.timeArrCache);
        this.timeArr = children.filter((it) => it.x === x + 1);
    }

    easyCopy(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(new Date(), current) > 0;
    };
    removeTime(index: number) {
        if (index === 0) {
            this.notification.create(
                "error",
                "删除时间",
                "无法删除首个时间节点，因为他是必须的！"
            );
            return;
        }

        if (this.timeArr.length <= 2) {
            this.notification.create(
                "error",
                "删除时间",
                "无法删除该时间，因为时间分支默认必须有两个节点！"
            );
            return;
        }

        this.modal.confirm({
            nzTitle: "删除时间?",
            nzContent: "删除当前时间节点，其子节点也会全部删除，确定要删除吗？",
            nzOnOk: () => {
                const removePnode = this.timeArr.splice(index, 1)[0];
                const children = this.pSrv.DB.childrenDeepFlatten({
                    id: removePnode.id,
                });
                const targetRemoveNodes = children.filter(
                    (it) => it.y === removePnode.y
                );
                const deleteYLevel = targetRemoveNodes.sort(
                    (a, b) => b.y - a.y
                )[0]["y"];
                const targetYLevel = deleteYLevel + 1;
                this.pSrv
                    .remove(targetRemoveNodes)
                    .move(targetYLevel, -1)
                    .updatePedges();
            },
        });
    }
    addTime() {
        if (this.timeArr.length >= this.maxBranchs) {
            this.notification.create(
                "error",
                "添加时间",
                `目前只允许添加 ${this.maxBranchs} 个分支！`
            );
            return;
        }
        const { x } = this.data;
        const { id, pid } = this.timeArr[this.timeArr.length - 1];
        const children = this.pSrv.DB.childrenDeepFlatten({ id });
        const deleteYLevel = children.sort((a, b) => b.y - a.y)[0]["y"];
        const targetYLevel = deleteYLevel + 1;

        const timePnod = this.nfSrv.createTimePnodeInCondition(
            x + 1,
            targetYLevel,
            pid
        );
        const helpPnode = this.nfSrv.createHelperPnode(
            x + 2,
            targetYLevel,
            timePnod.id
        );
        this.timeArr.push(timePnod);
        this.pSrv
            .move(targetYLevel, 1)
            .insert([timePnod, helpPnode])
            .updatePedges();
    }
}
